const { DataTypes, Model, Deferrable, Op } = require("sequelize");
const sequelize = require("../../db/sequelize");
const Category = require("../category/category");
const GoodsBanner = require("./goods_banner");
const GoodsSkusCard = require("./goods_skus_card");
const GoodsSkus = require("./goods_skus");
/**
 * 商品模型
 */
class Goods extends Model {
    /**
     * 获取商品列表
     */
    static async getJson(page, limit, tab,category_id,title) {
        let json = {};
        json["list"] = []
        await Goods.getGoods(page, limit, tab,category_id,title).then(async goods => {
            for (let i = 0; i < goods.length; i++) {
                json["list"].push(goods[i].toJSON())
            }
            json["cates"] = []
            await Category.findAll({
                where: {
                    category_id: 0
                },
                
            }).then(async row => {
                json["totalCount"] = await Goods.count()
                for (let i = 0; i < row.length; i++) {
                    let js = row[i].toJSON()
                    js["child"] = []
                    await Category.getChild(js).then(value => {
                        json["cates"].push(value)
                    })
                }

            })
        })
        return json
    }
    /**
     * 获取分页数据
     * @param {*} page 
     * @param {*} limit 
     * @returns 
     */
    static async getGoods(page, limit, tab,category_id,title) {
        let where = {}
        let paranoid=true
        //类型：all全部，checking审核中，saling出售中，off已下架，min_stock库存预警，delete回收站
        switch (tab) {
            case "checking":
                where["ischeck"] = 0
                break;
            case "saling":
                where["status"] = 1
                break
            case "off":
                where["status"] = 0
                break
            case "min_stock":
                where["stock"] ={}
                where.stock[Op.lt]=sequelize.col("min_stock")
                break
            case "delete":
                where["delete_time"]={}
                where.delete_time[Op.not]=null
                paranoid=false
                break
        }
        if (category_id) {
            where["category_id"]=category_id
        }
        if (title) {
            where["title"]={}
            where.title[Op.like]="%"+title+"%"
        }
        console.log("注意===============");
        let goods = await this.findAll({
            include: [
                {
                    model: Category
                }, {
                    model: GoodsBanner
                }, {
                    model: GoodsSkusCard
                }
            ],
            where: where,
            limit: Number(limit),
            offset: limit * page - limit,
            paranoid:paranoid,
            order:[['id',"DESC"]],
        })
        return goods
    }
    /**
     * 批量删除商品
     * @param {id列表} ids 
     */
    static async deleteAll(ids){
        return await this.destroy({
            where:{
                id:ids
            }
        })
    }
    /**
     * 批量恢复商品
     * @param {id列表} ids 
     */
    static async restores(ids){
        return await this.restore({
            where:{
                id:ids
            }
        })
    }
    static async resetCategoryId(category_id){
        await this.update({
            category_id:0
        },{
            where:{
                category_id:category_id
            }
        })
    }
    //分类关联产品列表
    static async getGoodsAsCategory(id,limit,page){
        let ls=await Category.findOne({
            include:[
                {
                    model:Goods,
                    attributes:["id","title","category_id","cover","order","create_time","update_time"],
                    limit:limit,
                    offset:limit*page-limit
                }
            ],
            where:{
                id:id
            }
        })
        let json=ls.toJSON()
        json["totalCount"]=await Goods.count({
            where:{
                category_id:id
            }
        })
        return json
    }
    //获取商品详情
    static async getGoodSkus(id){
        return await this.findOne({
            where:{
                id:id
            },
            include:[
                {
                    model:GoodsSkus,
                },{
                    model:GoodsBanner,
                    attributes:["url"]
                }
            ]
        })
    }
};
Goods.init({
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    //商品名称
    title: {
        type: DataTypes.STRING,
        allowNull: false
    },
    //分类id
    category_id: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    //封面
    cover: {
        type: DataTypes.STRING,
        allowNull: false
    },
    rating: {
        type: DataTypes.FLOAT
    },
    sale_count: {
        type: DataTypes.INTEGER
    },
    review_count: {
        type: DataTypes.INTEGER
    },
    min_price: {
        type: DataTypes.DECIMAL(10, 2),
        allowNull: false
    },
    min_oprice: {
        type: DataTypes.DECIMAL(10, 2),
        allowNull: false
    },
    desc: {
        type: DataTypes.STRING,
        allowNull: false
    },
    unit: {
        type: DataTypes.STRING,
        allowNull: false
    },
    stock: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    min_stock: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    ischeck: {
        type: DataTypes.TINYINT(1),
        defaultValue: 0
    },
    status: {
        type: DataTypes.TINYINT(1),
        defaultValue: 0
    },
    stock_display: {
        type: DataTypes.INTEGER,
        defaultValue: 1
    },
    express_id: {
        type: DataTypes.INTEGER
    },
    sku_type: {
        type: DataTypes.TINYINT(1),
        defaultValue: 0
    },
    sku_value: {
        type: DataTypes.STRING
    },
    content: {
        type: DataTypes.TEXT
    },
    discount: {
        type: DataTypes.FLOAT
    },
    order: {
        type: DataTypes.INTEGER,
        defaultValue: 50
    },
    type_id:{
        type:DataTypes.INTEGER
    }
}, {
    sequelize,
    paranoid: true,//设置偏执表
    modelName: "Goods",
    tableName: "goods",
    createdAt: "create_time",
    updatedAt: "update_time",
    deletedAt: "delete_time",
})
module.exports = Goods